package com.dahua.ui.user;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;


import com.dahua.R;
import com.dahua.ui.base.BaseActivity;

import java.io.File;
import java.util.Locale;


/**
 *
 */
public class ActivityDetailAct extends BaseActivity implements
        OnDismissListener {

    private TextView tvTitle;
    private WebView webView;
    private String url;
    private Context context;
    private Handler mHandler = new Handler();
    private JsResult result1;
    private boolean success = false;
    private int code = -1;
    Activity bean;
    String user_id = null;
    String type;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        init();
    }

    @SuppressLint("JavascriptInterface")
    private void init() {
        showLoadingDialog(); SharedPreferences sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
        user_id = sharedPreferences.getString("user_id", "null");

        type=getIntent().getStringExtra("type");
        url = "file:///android_asset/part2/" + getIntent().getStringExtra("url");
        context = ActivityDetailAct.this;
        webView = (WebView) findViewById(R.id.fu_webview);
        // 启用数据库
        webView.getSettings().setDatabaseEnabled(true);
        String dir = this.getApplicationContext()
                .getDir("database", Context.MODE_PRIVATE).getPath();
        // 设置定位的数据库路径
        webView.getSettings().setGeolocationDatabasePath(dir);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setAllowFileAccess(true);// 设置可以访问文件
//		webView.getSettings().setPluginState();
        webView.getSettings().setDomStorageEnabled(true);// 定位相关
        webView.getSettings().setGeolocationEnabled(true); // 启用定位
        webView.getSettings().setCacheMode(webView.getSettings().LOAD_NO_CACHE); // 不使用缓存
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);// 支持通过JS打开新窗口
        webView.addJavascriptInterface(new ShopJavaScriptInterface(), "demo");
        webView.requestFocus();
        webView.loadUrl(url);

        webView.setWebViewClient(new WebViewClient() {
            // 当点击链接时,希望覆盖而不是打开新窗口
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.i("5555", "shouldOverrideUrlLoading");
                if (url.contains("wtloginmqq")) {
                    return true;
                }else if(url.contains("dahua://openShare")){
                    String params = url.substring(url.indexOf("dahua://openShare?"),url.length());
                    shareToWhatsApp(params);
                    return true;
                }
                return true; // 返回true,代表事件已处理,事件流到此终止
            }

        });

        webView.setWebChromeClient(new WebChromeClient() {
            // 当WebView进度改变时更新窗口进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // Activity的进度范围在0到10000之间,所以这里要乘以100
                if (newProgress == 100) {
                    hideLoadingDialog();
                }
            }

            // 定位
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin,
                                                           GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }

            @Override
            // call when javascript request a popup window
            public boolean onJsAlert(WebView view, String url, String message,
                                     final JsResult result) {
                result1 = result;
                return true;
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                ActivityDetailAct.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            }

            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                ActivityDetailAct.this.startActivityForResult(
                        Intent.createChooser(i, "File Browser"),
                        FILECHOOSER_RESULTCODE);
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                ActivityDetailAct.this.startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
            }

            // For Android 5.0+
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                super.onShowFileChooser(webView, filePathCallback, fileChooserParams);
                mUploadCallbackAboveL = filePathCallback;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(
                        Intent.createChooser(i, "File Browser"),
                        FILECHOOSER_RESULTCODE);
                return true;
            }
        });


        webView.setDownloadListener(new DownloadListener() {

            @Override
            public void onDownloadStart(String url, String userAgent,
                                        String contentDisposition, String mimetype,
                                        long contentLength) {
                // TODO Auto-generated method stub
                Log.i("tag", "url=" + url);
                Log.i("tag", "userAgent=" + userAgent);
                Log.i("tag", "contentDisposition=" + contentDisposition);
                Log.i("tag", "mimetype=" + mimetype);
                Log.i("tag", "contentLength=" + contentLength);
                // download(url);
                // startService();
                // Uri uri = Uri.parse(url);
                // Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                // startActivity(intent);
            }
        });
    }

    private ValueCallback<Uri> mUploadMessage;
    private int FILECHOOSER_RESULTCODE = 9000;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }
        }else  if (requestCode == 1 & resultCode == 1) {
            showLoadingDialog();
            webView.loadUrl(url);
        }
    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != FILECHOOSER_RESULTCODE
                || mUploadCallbackAboveL == null) {
            return;
        }
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        mUploadCallbackAboveL.onReceiveValue(results);
        mUploadCallbackAboveL = null;
        return;
    }


    private ValueCallback<Uri[]> mUploadCallbackAboveL;


    private boolean isZh() {
        Locale locale = getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        if (language.endsWith("zh"))
            return true;
        else
            return false;
    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            Log.i("5555", "code===" + code);
            if (msg.what != 200) {
                webView.loadUrl("file:///android_asset/part2/html/error.html");
                success = false;
            } else {
                webView.loadUrl(msg.obj.toString()); // 加载新的url
                success = true;
            }
        }

    };

    /**
     * 跳转
     *
     */
    final class ShopJavaScriptInterface {

        ShopJavaScriptInterface() {
        }
        @JavascriptInterface
        public void jump(String id) {

        }
        @JavascriptInterface
        public void logout() {
            showLoadingDialog();
        }

    }

    public void refresh(View view) {
        if (!"".equals(webView.getUrl()) && webView.getUrl() != null) {
            webView.loadUrl(webView.getUrl());
        }
    }

    public void back(View view) {
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCoder, KeyEvent event) {
        if (keyCoder == KeyEvent.KEYCODE_BACK) {
            if (webView.canGoBack() && success) {
                webView.goBack(); // goBack()表示返回webView的上一页面
            } else {
                finish();
            }
            return true;
        }
        return false;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        // TODO Auto-generated method stub
        result1.confirm();
    }

    private void shareToWhatsApp(String params) {
        Log.i("TAG",params);
        if(!isPackageInstalled("com.whatsapp",this)){
            Toast.makeText(this,"Whatsapp have not been installed.",Toast.LENGTH_SHORT).show();
            return;
        }
        /**
         * Show share dialog BOTH image and text
         */
        File f = new File(Environment.getExternalStorageDirectory()+ File.separator + "yodo1_poster.jpg");
        Uri imageUri = Uri.parse(f.getAbsolutePath());
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        //Target whatsapp:
        shareIntent.setPackage("com.whatsapp");
        //Add text and then Image URI
        shareIntent.putExtra(Intent.EXTRA_TEXT, "this is text2");
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        shareIntent.setType("image/jpeg");
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(shareIntent);

//        Bitmap adv = BitmapFactory.decodeResource(getResources(), R.mipmap.system_message);
//        Intent share = new Intent(Intent.ACTION_SEND);
//        share.setType("image/jpeg");
//        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
//        adv.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//        File f = new File(Environment.getExternalStorageDirectory()
//                + File.separator + "trimedcard.jpg");
//        try {
//            f.createNewFile();
//            new FileOutputStream(f).write(bytes.toByteArray());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        share.putExtra(Intent.EXTRA_TEXT, "this is text");
//        share.putExtra(Intent.EXTRA_STREAM,
//                Uri.parse( Environment.getExternalStorageDirectory()+ File.separator+"trimedcard.jpg"));
//        if(isPackageInstalled("com.whatsapp",this)){
//            share.setPackage("com.whatsapp");
//            startActivity(Intent.createChooser(share, "Share Image"));
//
//        }else{
//            Toast.makeText(getApplicationContext(), "Please Install Whatsapp", Toast.LENGTH_LONG).show();
//        }

    }


    private boolean isPackageInstalled(String packagename, Context context) {
        PackageManager pm = context.getPackageManager();
        try {
            pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

}
